package com.hyou.springboot2.module.login;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.hyou.springboot.annotation.FormValidator;
import com.hyou.springboot.base.ResponseMessage;
import com.hyou.springboot.util.DigestUtil;
import com.hyou.springboot.util.ResponseMessageUtil;
import com.hyou.springboot2.consts.UserStatusConst;
import com.hyou.springboot2.dto.form.LoginForm;
import com.hyou.springboot2.dto.pojo.SysAccountDO;
import com.hyou.springboot2.dto.vo.LoginVO;
import com.hyou.springboot2.service.base.itfc.SysAccountService;

/**
 * 用户登录请求
 * 
 * @author FengChangshuo
 * @version 2.1.2 2018-11-01 14:33:55 初始创建
 */
@RestController
public class LoginController {
    
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    
    @Resource
    private SysAccountService sysAccountService;
    
    @FormValidator
    @PostMapping(path = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseMessage<LoginVO> login(@RequestBody LoginForm form) {
        log.debug("param LoginForm : {}", form);
        
        String userName = form.getUserName();
        String password = form.getPassword();
        String md5Password = DigestUtil.md5(password, userName);
        
        SysAccountDO paramBean = new SysAccountDO();
        paramBean.setAccount(userName);
        paramBean.setPassword(md5Password);
        SysAccountDO resultBean = sysAccountService.getByAccountAndPassword(paramBean);
        
        if (resultBean == null) {
            return ResponseMessageUtil.genFailResult("用户名或密码错误");
        }
        
        if (resultBean.getStatus() == UserStatusConst.DISABLED) {
            return ResponseMessageUtil.genFailResult("账号不可用");
        }
        
        return ResponseMessageUtil.genSuccessResult();
    }
    
}
